package com.zby.charity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zby.charity.common.BaseResponse;
import com.zby.charity.common.ErrorCode;
import com.zby.charity.common.ResultUtils;
import com.zby.charity.entity.LectureCountEntity;
import com.zby.charity.entity.LectureEntity;
import com.zby.charity.entity.LectureYearAndMonth;
import com.zby.charity.exception.BusinessException;
import com.zby.charity.service.LectureCountService;
import com.zby.charity.service.LectureService;
import com.zby.charity.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zby
 * @email 2069189112@qq.com
 * @date 2025-01-22 13:36:24
 */
@Slf4j
@RestController
@RequestMapping("charity/lecture")
public class LectureController {
    @Resource
    private LectureService lectureService;
    @Autowired
    private LectureCountService lectureCountService;

    @PostMapping("/addLecture")
    public BaseResponse<Boolean> addLecture(@RequestBody LectureEntity lectureEntity) {
        String title = lectureEntity.getTitle();
        String name = lectureEntity.getName();
        if (StringUtils.isAnyBlank(title, name))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题和姓名不能为空");
        int count = lectureEntity.getCount();
        if (count <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "人数必须大于0");
        int continueday = lectureEntity.getContinueday();
        if (continueday <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "讲座天数必须大于0");
        int continuetime = lectureEntity.getContinuetime();
        if (continuetime <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "讲座时长必须大于0");
        boolean save = lectureService.save(lectureEntity);
        if (!save)
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加讲座失败");
        return ResultUtils.success(true);
    }

    @PostMapping("/listLecture")
    public BaseResponse<List<LectureEntity>> listLecture(@RequestBody LectureYearAndMonth lectureYearAndMonth) {
        String yearStr = lectureYearAndMonth.getYear();
        String monthStr = lectureYearAndMonth.getMonth();
        if (StringUtils.isAnyBlank(yearStr, monthStr))
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        int year = Integer.parseInt(yearStr);
        int month = Integer.parseInt(monthStr);

        Date[] dates = DateUtils.getMonthStartAndEndDates(year, month);
        Date startDate = dates[0];
        Date endDate = dates[1];
        List<LectureEntity> list = lectureService.list();
        if (list == null)
            return ResultUtils.success(Collections.emptyList());

        // 过滤出在当年当月的讲座
        List<LectureEntity> filteredList = list.stream()
                .filter(lectureEntity -> {
                    Date stime = lectureEntity.getStime();
                    return stime != null &&
                            !stime.after(endDate) && !stime.before(startDate);
                })
                .collect(Collectors.toList());

        return ResultUtils.success(filteredList);
    }

    @PostMapping("/list")
    public BaseResponse<List<LectureEntity>> list() {
        List<LectureEntity> list = lectureService.list().stream().map(lectureEntity -> {
                    Integer id = lectureEntity.getId();
                    Integer hasjoin = Math.toIntExact(lectureCountService.
                            count(new QueryWrapper<LectureCountEntity>().eq("lid", id)));
                    lectureEntity.setHasjoin(hasjoin);
                    return lectureEntity;
                }).sorted(Comparator.comparing(LectureEntity::getStime).reversed())
                .collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @GetMapping("/getLecture")
    public BaseResponse<LectureEntity> getLecture(@RequestParam int id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LectureEntity lectureEntity = lectureService.getById(id);
        if (lectureEntity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(lectureEntity);
    }

    @GetMapping("/deleteLecture")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> deleteLecture(@RequestParam int id) {
        checkId(id);
        try {
            boolean b = lectureService.removeById(id);
            if (!b) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除讲座失败，ID: " + id);
            }
            deleteLectureJoin(id);
            log.info("成功删除讲座，ID: {}", id);
            return ResultUtils.success(true);
        } catch (BusinessException e) {
            log.error("删除讲座失败，ID: {}, 错误信息: {}", id, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("删除讲座时发生未知错误，ID: {}", id, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        }
    }

    private void checkId(int id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的ID: " + id);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean deleteLectureJoin(int lid) {
        checkId(lid);
        try {
            boolean b = lectureCountService.remove(new QueryWrapper<LectureCountEntity>().eq("lid", lid));
            if (!b) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除讲座关联数据失败，LID: " + lid);
            }
            log.info("成功删除讲座关联数据，LID: {}", lid);
            return true;
        } catch (BusinessException e) {
            log.error("删除讲座关联数据失败，LID: {}, 错误信息: {}", lid, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("删除讲座关联数据时发生未知错误，LID: {}", lid, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        }
    }

    @PostMapping("/editLecture")
    public BaseResponse<Boolean> editLecture(@RequestBody LectureEntity lectureEntity) {
        if (lectureEntity == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = lectureService.updateById(lectureEntity);
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改讲座失败");
        }
        return ResultUtils.success(true);
    }
}
